package com.kevin.kitchenshow2;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.kevin.kitchenshow2.adapter.CategoryAdapter;
import com.kevin.kitchenshow2.adapter.SubcateAdapter;
import com.kevin.kitchenshow2.entity.Category;
import com.kevin.kitchenshow2.entity.Item;
import com.kevin.kitchenshow2.entity.SubCategory;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class KitchenShow extends Activity {
	private ListView lsvCategory;
	private ListView lsvSubcate;
	private LinearLayout layContent;
	private ProgressDialog diaCat;
	private ProgressDialog diaSubcat;
	private ProgressDialog diaItem;
	public static List<Category> lstCategory;
	public static List<SubCategory> lstSubcate;
	public static List<Item> lstItem;
	public static final int CATEGORY_VIEW = 0;
	public static final int SUBCATEGORY_VIEW = 1;
	public static final int ITEM_VIEW = 2;
	private int viewStatus = 0;
	private int currentCategory;
	private int currentSubcate;
	private int currentItem;
	private View categoryView;
	private View subcateView;
	private View itemView;
	private LayoutInflater inflater;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		inflater = LayoutInflater.from(this);
		final View mainView = inflater.inflate(R.layout.kitchen_show, null);
		// ListView lsvCatList=(ListView)inflater.inflate(R.layout., root)
		categoryView = inflater.inflate(R.layout.category_list, null);
		lsvCategory = (ListView) categoryView.findViewById(R.id.lsvCategory);
		layContent = (LinearLayout) mainView.findViewById(R.id.layContent);
		layContent.addView(categoryView);

		diaCat = ProgressDialog.show(this, "Loading infomation from server.",
				"Wait one second please.", true, true);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				URL xmlUrl = null;
				try {
					xmlUrl = new URL(getResources().getString(
							R.string.xmlsource));
				} catch (Exception ex) {
					Toast.makeText(getApplicationContext(),
							"Application error!", Toast.LENGTH_SHORT).show();
					ex.printStackTrace();
					System.exit(0);
				}
				InputStream xmlStream = null;
				if (xmlUrl != null) {

					try {
						xmlStream = xmlUrl.openStream();
					} catch (IOException e) {
						Toast.makeText(getApplicationContext(),
								"Network error!", Toast.LENGTH_SHORT).show();
						e.printStackTrace();
						System.exit(0);
					}
				}
				Document doc = null;
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder dbd = null;
				try {
					dbd = dbf.newDocumentBuilder();
				} catch (ParserConfigurationException e) {
					Toast.makeText(getApplicationContext(), "Document error!",
							Toast.LENGTH_SHORT).show();

					e.printStackTrace();
					System.exit(0);
				}
				if (dbd != null && xmlStream != null) {
					try {
						doc = dbd.parse(xmlStream);
					} catch (SAXException e) {
						Toast.makeText(getApplicationContext(),
								"Document structure error!", Toast.LENGTH_SHORT)
								.show();

						e.printStackTrace();
						System.exit(0);
					} catch (IOException e) {
						Toast.makeText(getApplicationContext(),
								"Document not found error!", Toast.LENGTH_SHORT)
								.show();

						e.printStackTrace();
						System.exit(0);
					}
				}
				Node rootNode = null;
				List<Node> lstCateNode = null;
				if (doc != null) {
					rootNode = doc.getFirstChild();
					lstCateNode = getChildElementNode(rootNode);
				}
				lstCategory = new Vector<Category>();
				for (int i = 0; i < lstCateNode.size(); i++) {
					Category cat = new Category(lstCateNode.get(i),
							KitchenShow.this);
					lstCategory.add(cat);
				}
				diaCat.dismiss();
				// setContentView(mainView);

			}
		}).start();
		diaCat.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
				CategoryAdapter catAdapter = new CategoryAdapter(
						KitchenShow.this, lstCategory);
				lsvCategory.setAdapter(catAdapter);

			}

		});
		lsvCategory.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				// TODO Auto-generated method stub
				viewStatus = SUBCATEGORY_VIEW;
				currentCategory = position;
				layContent.removeAllViews();
				subcateView = inflater.inflate(R.layout.subcategory_list, null);
				lsvSubcate = (ListView) subcateView
						.findViewById(R.id.lsvSubcate);
				layContent.addView(subcateView);
				ImageButton btnBack = (ImageButton) subcateView
						.findViewById(R.id.btnBack);
				btnBack.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						layContent.removeAllViews();
						layContent.addView(categoryView);
					}

				});

				diaSubcat = ProgressDialog.show(KitchenShow.this,
						"Please wait...",
						"Loading subcategories list from server.", true, true);
				new Thread(new Runnable() {

					@Override
					public void run() {
						List<Node> lstSubcateNode = getChildElementNode(lstCategory
								.get(position).getXmlNode());
						lstSubcate = new Vector<SubCategory>();
						for (int i = 0; i < lstSubcateNode.size(); i++) {
							SubCategory subcate = new SubCategory(
									lstSubcateNode.get(i), KitchenShow.this);
							lstSubcate.add(subcate);
						}
						diaSubcat.dismiss();
					}
				}).start();
				diaSubcat.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface arg0) {
						SubcateAdapter adapter = new SubcateAdapter(
								KitchenShow.this, lstSubcate);
						lsvSubcate.setAdapter(adapter);
					}

				});

			}

		});
		setContentView(mainView);
	}

	public static Node getChildNodeAt(Node fa, int pos) {
		NodeList children = fa.getChildNodes();
		int c = 0;
		for (int i = 0; i < children.getLength(); i++) {
			if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
				if (c == pos) {
					return children.item(i);
				}
			}
		}
		return null;
	}

	public static List<Node> getChildElementNode(Node fa) {
		NodeList children = fa.getChildNodes();
		List<Node> lst = new Vector<Node>();
		for (int i = 0; i < children.getLength(); i++) {
			if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
				lst.add(children.item(i));
			}
		}
		return lst;

	}

	public static String getAttibuteOfNode(Node cNode, String attrName) {
		NamedNodeMap attrMap = cNode.getAttributes();
		return attrMap.getNamedItem(attrName).getNodeValue();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.kitchen_show, menu);
		return true;
	}
}
